package com.outdoor.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.outdoor.model.dto.response.ApiResponse;
import com.outdoor.model.entity.User;
import com.outdoor.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 * 
 * @author OutdoorTeam
 * @date 2025-05-18
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户相关接口")
public class UserController {

    private final UserService userService;

    @PostMapping
    @Operation(summary = "创建用户", description = "创建新用户")
    public ApiResponse<User> createUser(@Valid @RequestBody User user) {
        log.debug("创建用户请求: {}", user.getUsername());
        return ApiResponse.success("用户创建成功", userService.createUser(user));
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取用户", description = "根据ID获取用户信息")
    public ApiResponse<User> getUserById(@PathVariable Long id) {
        log.debug("获取用户请求: ID={}", id);
        return ApiResponse.success(userService.getUserById(id));
    }

    @GetMapping("/username/{username}")
    @Operation(summary = "根据用户名获取用户", description = "根据用户名获取用户信息")
    public ApiResponse<User> getUserByUsername(@PathVariable String username) {
        log.debug("获取用户请求: 用户名={}", username);
        return ApiResponse.success(userService.getUserByUsername(username));
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新用户", description = "更新用户信息")
    public ApiResponse<User> updateUser(@PathVariable Long id, @Valid @RequestBody User user) {
        log.debug("更新用户请求: ID={}", id);
        return ApiResponse.success("用户更新成功", userService.updateUser(id, user));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户", description = "删除用户")
    public ApiResponse<Void> deleteUser(@PathVariable Long id) {
        log.debug("删除用户请求: ID={}", id);
        userService.deleteUser(id);
        return ApiResponse.success("用户删除成功", null);
    }

    @GetMapping
    @Operation(summary = "获取用户列表", description = "分页获取用户列表")
    public ApiResponse<IPage<User>> listUsers(@RequestParam(defaultValue = "1") long current,
                                            @RequestParam(defaultValue = "10") long size) {
        log.debug("获取用户列表请求: 当前页={}, 每页记录数={}", current, size);
        Page<User> page = new Page<>(current, size);
        return ApiResponse.success(userService.listUsers(page));
    }
} 